package device

import (
	"context"
	"device-admin/internal/app/grpc/protoc/devicec"
	"device-admin/internal/app/grpc/service/pubsub"
	"device-admin/internal/dal"
	"device-admin/internal/dao"
	"encoding/base64"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/helper"
	"192.168.1.75/go-pkg/logx"
	"google.golang.org/protobuf/proto"
)

type Media struct{}

// Media 设置音量
func (Media) SetVolume(
	ctx context.Context,
	robotID, terminalType string,
	volumePercent int,
	volumetype int,
) error {
	if robotID == "" {
		return errorx.New("机器id不能为空", -1)
	}
	if terminalType == "" {
		return errorx.New("终端类型不能为空", -1)
	}
	logx.Info(
		context.Background(),
		"SetVolume Media",
		logx.String("robot_id", robotID),
		logx.String("TerminalType", terminalType),
		logx.Int("VolumePercent", volumePercent),
		logx.Int("Volumetype", volumetype),
	)
	dao.Terminal{}.SetVolume(
		ctx,
		dal.Q,
		robotID, terminalType,
		volumePercent,
		volumetype,
	)
	// 下发proto消息，设置终端的声音
	sendMsg := &devicec.Msg{}
	sendMsg.Ack = 0
	sendMsg.Seq = helper.RandString(16)
	volumeSettingReq := &devicec.VolumeSettingReq{}
	volumeSettingReq.Percent = int32(volumePercent)
	volumeSettingReq.Volumetype = int32(volumetype)
	sendMsg.Name = string(volumeSettingReq.ProtoReflect().Descriptor().FullName())
	sendMsg.Content, _ = proto.Marshal(volumeSettingReq)
	// protobuf序列化
	bytes, _ := proto.Marshal(sendMsg)
	pubsub.CMDPublish(robotID, terminalType, "msg", base64.StdEncoding.EncodeToString(bytes))
	return nil
}
func (Media) GetVolume(
	ctx context.Context,
	robotID, terminalType string, volumetype int,
) (int, error) {
	if robotID == "" {
		return 0, errorx.New("机器id不能为空", -1)
	}
	if terminalType == "" {
		return 0, errorx.New("终端类型不能为空", -1)
	}
	volume := dao.Terminal{}.GetVolumeSetting(ctx, dal.Q, robotID, terminalType, volumetype)
	return volume, nil
}
